package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.gxnu.edu.cn.ttxxt.entity.Friendship;
import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.mapper.FavoriteRepository;
import com.gxnu.edu.cn.ttxxt.mapper.FriendshipRepository;
import com.gxnu.edu.cn.ttxxt.mapper.NotificationRepository;
import com.gxnu.edu.cn.ttxxt.mapper.UserRepository;
import com.gxnu.edu.cn.ttxxt.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendshipRepository friendshipRepository;

    @Autowired
    private FriendshipRepository favoriteRepository;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private NotificationRepository notificationRepository;

    @Override
    @Transactional
    public void sendFriendRequest(Long senderId, Long receiverId, String message) {
        // 检查是否已是好友
        if (friendshipRepository.existsByUserIdAndFriendId(senderId, receiverId)) {
            throw new IllegalArgumentException("你们已经是好友了");
        }

        // 检查是否已发送过请求
        if (notificationRepository.existsBySenderIdAndReceiverIdAndType(senderId, receiverId, 1)) {
            throw new IllegalArgumentException("已发送过好友请求，请等待对方处理");
        }

        // 创建通知
        Notifications notifications = new Notifications();
        notifications.setReceiverId(receiverId);
        notifications.setSenderId(senderId);
        notifications.setType(1); // 好友请求
        notifications.setContent(message != null ? message : "我想添加你为好友");
        notifications.setStatus(1); // 未处理
        notifications.setCreateTime(new Date());
      System.out.println(notifications.toString());
        notificationRepository.insert(notifications);
    }

    @Override
    @Transactional
    public void acceptFriendRequest(Long receiverId, Long senderId) {
        // 处理通知
        Notifications notifications = (Notifications) notificationRepository.findBySenderIdAndReceiverIdAndType(senderId, receiverId, 1)
                .orElseThrow(() -> new IllegalArgumentException("未找到好友请求"));

        notifications.setStatus(3); // 已处理
        notifications.setProcessTime(new Date());
        notificationRepository.updateById(notifications);

        // 创建双向好友关系
        createFriendship(receiverId, senderId);
        createFriendship(senderId, receiverId);

        // 发送通知告知对方已通过
        Notifications acceptNotifications = new Notifications();
        acceptNotifications.setReceiverId(senderId);
        acceptNotifications.setSenderId(receiverId);
        acceptNotifications.setType(2); // 好友请求通过
        acceptNotifications.setContent("已接受你的好友请求");
        acceptNotifications.setStatus(2); // 已读
        acceptNotifications.setCreateTime(new Date());
        acceptNotifications.setProcessTime(new Date());
        notificationRepository.insert(acceptNotifications);
    }

    @Override
    @Transactional
    public void rejectFriendRequest(Long receiverId, Long senderId) {
        // 处理通知
        Notifications notifications = (Notifications) notificationRepository.findBySenderIdAndReceiverIdAndType(senderId, receiverId, 1)
                .orElseThrow(() -> new IllegalArgumentException("未找到好友请求"));

        notifications.setStatus(3); // 已处理
        notifications.setProcessTime(new Date());
        notificationRepository.updateById(notifications);

        // 发送拒绝通知
        Notifications rejectNotifications = new Notifications();
        rejectNotifications.setReceiverId(senderId);
        rejectNotifications.setSenderId(receiverId);
        rejectNotifications.setType(3); // 好友请求拒绝
        rejectNotifications.setContent("拒绝了你的好友请求");
        rejectNotifications.setStatus(2); // 已读
        rejectNotifications.setCreateTime(new Date());
        rejectNotifications.setProcessTime(new Date());
        notificationRepository.insert(rejectNotifications);
    }

    @Override
    @Transactional
    public void deleteFriend(Long userId, Long friendId) {
        // 删除双向好友关系
        friendshipRepository.deleteByUserIdAndFriendId(userId, friendId);
        friendshipRepository.deleteByUserIdAndFriendId(friendId, userId);
        favoriteRepository.deleteByUserIdAndFriendId(userId, friendId);
        favoriteRepository.deleteByUserIdAndFriendId(friendId, userId);
    }

    @Override
    @Transactional
    public void blockFriend(Long userId, Long friendId) {
        // 更新好友状态为拉黑
        Friendship friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId)
                .orElseThrow(() -> new IllegalArgumentException("好友关系不存在"));

        friendship.setStatus(3); // 已拉黑
        friendship.setUpdateTime(new Date());
        friendshipRepository.updateById(friendship);
    }

    @Override
    @Transactional
    public void unblockFriend(Long userId, Long friendId) {
        // 更新好友状态为正常
        Friendship friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId)
                .orElseThrow(() -> new IllegalArgumentException("好友关系不存在"));

        friendship.setStatus(1); // 正常
        friendship.setUpdateTime(new Date());
        friendshipRepository.updateById(friendship);
    }

    @Override
    public List<Friendship> getFriends(Long userId) {
        // 获取所有状态正常的好友
        return friendshipRepository.findByUserIdAndStatus(userId, 1);
    }

    @Override
    public List<Friendship> getBlockedFriends(Long userId) {
        // 获取所有被拉黑的好友
        return friendshipRepository.findByUserIdAndStatus(userId, 3);
    }

    @Override
    @Transactional
    public void updateFriendRemark(Long userId, Long friendId, String remark) {
        Friendship friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId)
                .orElseThrow(() -> new IllegalArgumentException("好友关系不存在"));

        friendship.setRemark(remark);
        friendship.setUpdateTime(new Date());
        friendshipRepository.updateById(friendship);
    }

    @Override
    @Transactional
    public void updateFriendGroup(Long userId, Long friendId, String groupName) {
        Friendship friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId)
                .orElseThrow(() -> new IllegalArgumentException("好友关系不存在"));

        friendship.setGroupName(groupName);
        friendship.setUpdateTime(new Date());
        friendshipRepository.updateById(friendship);
    }

    private void createFriendship(Long userId, Long friendId) {
        Users friend = userRepository.selectById(friendId);
        if (friend == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        Friendship friendship = new Friendship();
        friendship.setUserId(userId);
        friendship.setFriendId(friendId);
        friendship.setRemark(friend.getUsername());
        friendship.setGroupName("我的好友");
        friendship.setStatus(1); // 正常
        friendship.setCreateTime(new Date());
        friendship.setUpdateTime(new Date());

        friendshipRepository.insert(friendship);
    }
}